import React, { Component } from "react";
import {
  StyleSheet,
  View,
  Text,
  Image,
  TouchableOpacity,
  FlatList
} from "react-native";

import { connect } from "react-redux";
import HeaderDefault from "../../components/header/HeaderDefault";

import Modal from "../../components/ModalBox";
import { getTodayPoTask } from "../../netServer/perform";
import { Empty } from "../../components/Empty/Empty";
import { dateTransform } from "../../utils/utils_date";
import { submitExeTask } from "../../netServer/advicePerform";
import Toast from "react-native-simple-toast";

class OralMedicine extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectOralMedic: null,
      taskList: [],
      isFresh: false
    };
  }
  static navigationOptions = ({ navigation }) => ({
    header: <HeaderDefault backBtnOnPress={navigation.goBack} title="口服药" />
  });

  _keyExtractor = (item, index) => "koufuyao" + index;

  _separator = () => {
    return <View style={{ height: 1, backgroundColor: "#efefef" }} />;
  };

  _ListEmptyComponent = () => {
    return <Empty titleStr="暂时没有相关的数据" />;
  };

  componentDidMount() {
    this._loadData();
  }

  _refreshData = () => {
    this.setState({
      isFresh: true
    });
    this._loadData();
  };

  _loadData = () => {
    let { user_id } = this.props.user_info;
    let params = new FormData();
    params.append("userId", user_id);

    getTodayPoTask(params, resp => {
      let { code, data = [], msg } = resp;

      if (code == 0) {
        this.setState({
          taskList: data,
          isFresh: false
        });
      } else {
        this.setState({
          isFresh: false
        });
      }
    });
  };

  _commitTask = () => {
    let { user_id } = this.props.user_info;
    let params = new FormData();
    params.append("userId", user_id);

    let { main_task_id, task_id } = this.state.selectOralMedic;

    params.append("mainTaskId", main_task_id);
    params.append("taskIds[0]", task_id);

    submitExeTask(params, resp => {
      let { code, data = [], msg } = resp;

      if (code == 0) {
        this._loadData();
        Toast.showWithGravity("提交数据成功", Toast.LONG, Toast.CENTER);
        this.myModel.close();
      } else {
        Toast.showWithGravity(msg, 1, Toast.CENTER);
      }
    });
  };

  _renderItem = ({ item }) => {
    let { use_time, advList = [], status, bed_no } = item;

    let dt = use_time ? new Date(use_time.replace(/-/g, "/")) : null;

    return (
      <TouchableOpacity
        onPress={() => {
          if (status === "待执行") {
            this.setState({
              selectOralMedic: item
            });
            this.myModel.open();
          }
        }}
      >
        <View
          style={{
            width: screenWidth,
            backgroundColor: "white",
            borderBottomColor: "#efefef",
            borderBottomWidth: 1,
            flexDirection: "row",
            alignItems: "center"
          }}
        >
          <Text
            style={{
              color: "blue",
              fontSize: 16,
              width: 60,
              textAlign: "center"
            }}
          >
            {dt ? dateTransform(dt, "hh:mm") : null}
          </Text>

          <View style={{ flex: 1 }}>
            {advList.map((value, index) => {
              return (
                <View
                  key={"advlist" + index}
                  style={{
                    paddingLeft: 10,
                    borderTopWidth: index > 0 ? 1 : 0,
                    borderTopColor: "#efefef"
                  }}
                >
                  <Text style={{ lineHeight: 30 }}>{value.medName}</Text>
                  <Text style={{ lineHeight: 30 }}>
                    {value.standard}/{value.use_unit} {value.measure}
                  </Text>
                </View>
              );
            })}
          </View>
          <View
            style={{
              width: 80,
              height: 80,
              paddingTop: 10,
              paddingBottom: 10,
              justifyContent: "center",
              alignItems: "center"
            }}
          >
            <Text style={{ lineHeight: 30, fontWeight: "bold" }}>{bed_no}</Text>
            <Text style={{ lineHeight: 30, color: "#e30000" }}>{status}</Text>
          </View>
        </View>
      </TouchableOpacity>
    );
  };

  _headerComponent() {
    return (
      <View
        style={{
          width: screenWidth,
          height: 30,
          paddingLeft: 10,
          paddingRight: 10,
          flexDirection: "row",
          justifyContent: "space-between",
          alignItems: "center",
          borderBottomColor: "#efefef",
          borderBottomWidth: 1
        }}
      >
        <Text>时间</Text>
        <Text>药品名</Text>
        <Text>床号/状态</Text>
      </View>
    );
  }

  renderModalContent() {
    if (this.state.selectOralMedic) {
      let { ptInfo = [], advList } = this.state.selectOralMedic;

      return (
        <View style={{ flex: 1 }}>
          <View
            style={{
              width: screenWidth,
              height: 50,
              flexDirection: "row-reverse",
              alignItems: "center"
            }}
          >
            <TouchableOpacity
              onPress={() => {
                this.myModel.close();
              }}
              style={{
                width: 50,
                height: 50,
                justifyContent: "center",
                alignItems: "center"
              }}
            >
              <Image
                style={{ width: 30, height: 30 }}
                source={require("./src/guanbi.png")}
              />
            </TouchableOpacity>
          </View>

          {/* 患者信息 */}
          <View
            style={{
              width: screenWidth,
              height: 30,
              paddingRight: 10,
              paddingLeft: 10,
              flexDirection: "row",
              justifyContent: "space-between"
            }}
          >
            <Text style={{ fontSize: 16 }}>{ptInfo.name}</Text>
            <Text style={{ color: "red", fontSize: 16 }}>{ptInfo.bed_no}</Text>
          </View>
          <View
            style={{
              width: screenWidth,
              height: 30,
              paddingRight: 10,
              paddingLeft: 10,
              flexDirection: "row",
              justifyContent: "space-between"
            }}
          >
            <Text style={{ fontSize: 16 }}>
              {ptInfo.sex === 1 ? "男" : "女"}/{ptInfo.age}
            </Text>
            <Text>{ptInfo.inhosp_no}</Text>
            <Text style={{ color: "red", fontSize: 16 }}>
              {ptInfo.grade_name}
            </Text>
          </View>

          <View
            style={{
              width: screenWidth,
              height: 30,
              color: "red",
              paddingRight: 10,
              paddingLeft: 10,
              borderBottomColor: "#efefef",
              borderBottomWidth: 1
            }}
          >
            <Text style={{ fontSize: 16, color: "#a40000" }}>
              {ptInfo.allergy}
            </Text>
          </View>

          {/* 药品信息 */}
          <View
            style={{
              flex: 1,
              paddingLeft: 10,
              borderBottomColor: "#efefef",
              borderBottomWidth: 1
            }}
          >
            {advList.map((value, index) => {
              return (
                <View
                  key={"advlist" + index}
                  style={{
                    borderTopWidth: index > 0 ? 1 : 0,
                    borderTopColor: "#efefef"
                  }}
                >
                  <Text style={{ lineHeight: 30 }}>{value.medName}</Text>
                  <Text style={{ lineHeight: 30 }}>
                    {value.standard}/{value.use_unit} {value.measure}
                  </Text>
                </View>
              );
            })}
          </View>
          <TouchableOpacity
            onPress={this._commitTask}
            style={{
              width: screenWidth,
              height: 45,
              backgroundColor: "#1296db",
              justifyContent: "center",
              alignItems: "center"
            }}
          >
            <Text style={{ color: "white", fontSize: 16 }}>确定</Text>
          </TouchableOpacity>
        </View>
      );
    } else {
      return <View />;
    }
  }

  render() {
    return (
      <View style={styles.container}>
        {this._headerComponent()}

        <FlatList
          style={{ flex: 1 }}
          refreshing={this.state.isFresh}
          onRefresh={this._refreshData}
          ListEmptyComponent={this._ListEmptyComponent}
          ItemSeparatorComponent={this._separator}
          data={this.state.taskList}
          keyExtractor={this._keyExtractor}
          renderItem={this._renderItem}
        />

        <Modal
          style={styles.modal3}
          position={"bottom"}
          backdropPressToClose={false}
          swipeToClose={false}
          ref={md => (this.myModel = md)}
        >
          {this.renderModalContent()}
        </Modal>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "white"
  },

  modal3: {
    height: 300,
    width: screenWidth
  }
});

function select(store) {
  return { user_info: store.userInfo.user_info };
}

export default connect(select)(OralMedicine);
